package haust;

import java.io.IOException;
import java.util.ArrayList;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;

public class TextureManager{
	private static final String TEXTUREPATH = "textures/";
	private static ArrayList<TextureContainer> textures = new ArrayList<TextureContainer>();
	private static Texture textureNotFound;
	
	/**
	 * 
	 */
	private TextureManager(){
	}
	
	/**
	 * Tries to load "texturenotfound.png" <br/>
	 * Which will be returned by getTextureByName if no texture is found with that name
	 */
	public static void Initialize()
	{
		addTexture("texturenotfound.png");
		textureNotFound = getTextureByName("texturenotfound.png");
	}
	
	
	/**
	 * 
	 * @param textureName
	 */
	public static void addTexture(String textureName) {
		try {
			Texture texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream(TEXTUREPATH+textureName));
			textures.add(new TextureContainer(textureName, texture));
		} catch (IOException e) {
			System.out.println("Error when trying to add texture: " + textureName);
			e.printStackTrace();
		}
	}
	
	/**
	 * Finds the texture given a textureId
	 * @param textureId
	 * @return Texture
	 */
	public static Texture getTextureById(int textureId){
		for(int i=0; i<textures.size(); i++){
			if(textures.get(i).getTextureId()==textureId){
				return textures.get(i).getTexture();
			}
		}
		
		return textureNotFound;
	}

	/** 
	 * Finds the texture by using the given name <br/>
	 * If not it will return textureNotFound, which should be "texturenotfound.png" <br/>
	 * @param textureName
	 * @return Texture
	 */
	public static Texture getTextureByName(String textureName){
		for(int i=0; i<textures.size(); i++){
			if(textureName.equalsIgnoreCase(textures.get(i).getTextureName())){
				return textures.get(i).getTexture();
			}
		}

		return textureNotFound;
	}
	
	/**
	 * Unloads every texture in the textures arraylist
	 */
	public static void Destroy()
	{
		for( int i = 0; i < textures.size(); ++i )
		{
			textures.get(i).getTexture().release();
		}
		
		textures.clear();
	}

}